import config

outPath = config.path + "\\" + "index.html"
tempArr = []  # 临时索引数组
fatherNameIndex = []  # 父索引


# 添加索引 (父目录,文件名，解释)
def addIndex(pathName: str, explain: str):
    global tempArr
    tempArr.append([pathName, explain])
    return


# 添加父目录索引
def addFatherIndex(fatherName: str):
    global tempArr
    global fatherNameIndex
    if len(tempArr) == 0:  # 没有数据则跳过
        return
    # 有数据
    fatherNameIndex.append([fatherName, tempArr])
    tempArr = []  # 初始化
    return


# 保存html
def save():
    global fatherNameIndex
    f = open(outPath, 'wb')
    content = '<html>' \
              '<head>' \
              '<title>索引列表</title>' \
              '<meta name="description" content="索引列表" /><!--简介-->' \
              '<meta name="keywords" content="索引列表,单片机" /><!--索引关键字-->' \
              '<meta charset="UTF-8">' \
              '<style>' \
              'table {' \
              'border: 1px solid #000;' \
              '}' \
              'tr:first-child{' \
              'font-weight: 900;' \
              'font-family: "微软雅黑";' \
              '}' \
              'td{' \
              'border: 1px solid #000;' \
              'padding: 5px;' \
              'width: 150vh;' \
              '}' \
              'td:first-child{' \
              'width: 30vh;' \
              '}' \
              'body{' \
              'padding: 10px;' \
              '}' \
              '</style>' \
              '</head>' \
              '<body>' \
              '<h1>合泰单片机例子索引</h1>' \
              '<p>By: Lamzy</p><hr />'
    for fatherIndex in fatherNameIndex:#遍历数组
        fatherName = fatherIndex[0] #父目录名
        temps = fatherIndex[1]#内容集合
        content += '<h2><a href="file://localhost/' + config.getPath() + "\\" + fatherName + '" title="打开目录" target="_black">' + fatherName + '</a><h2>' \
                   '<table>' \
                   '<tr>' \
                   '<td>文件名</td>' \
                   '<td>解释</td>' \
                   '</tr>'
        for temp in temps:#遍历数组
            pathName = temp[0]#文件名
            explain = temp[1]#解释
            content += '<tr>' \
                       '<td><a href="file://localhost/' + config.getPath() + "\\" + fatherName + "\\" + pathName + '" title="打开目录" target="_black">' + pathName + '</a></td>' \
                       '<td><a href="file://localhost/' + config.getPath() + "\\" + fatherName + "\\" + pathName + "\\readme_zh.txt" + '" title="' + explain + '" targer="_black">' + getContent(explain,128) + '</a></td>' \
                       '</tr>'
        content += '</table>'
    content += '</body>' \
               '</html>'
    f.write(content.encode('utf-8'))
    f.close()
    return

#获取指定字符串长度
def getContent(text:str , len:int):
    re = text.replace("\n","").replace("\r","").replace(" ","").replace("/**","")
    re = re[0:len]
    return re
